package cn.hesion;
/**
 * ClassName: FlinkTableDemo <br/>
 * Description: <br/>
 * date: 2021/9/11 7:06 下午<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import static org.apache.flink.table.api.Expressions.$;
import org.apache.flink.types.Row;
/**
 * FlinkTable的代码编写
 * @author: hesion
 * @create: 2021-09-11 19:06
 **/
public class FlinkTableDemo {
    public static void main(String[] args) throws Exception {
            //环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建tEnv
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        //获取流式数据
        DataStreamSource<Tuple2<String, Integer>> data = env.addSource(new SourceFunction<Tuple2<String, Integer>>() {
            int num = 0;

            @Override
            public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception {
                while (true) {
                    ctx.collect(new Tuple2<>("name" + num, num));
                    num++;
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {

            }
        });

        //将流式数据源作为Table
        Table table = tEnv.fromDataStream(data, $("name"), $("age"));

        //对Table中的数据做查询
        Table name = table.select($("name"));
        DataStream<Tuple2<Boolean, Row>> res = tEnv.toRetractStream(name, Row.class);
        res.print();
        env.execute();
    }
}
